#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

from console import debug
import MySQLdb
from random import randint

class db:
    def __init__(self):
        pass
    def connect(self, database):
        self.connection = MySQLdb.connect (host = "localhost",
                                            user = "talk",
                                            passwd = "",
                                            db = database)
        debug(self.connection)
    def disconnect(self):
        self.connection.close()
        debug(self.connection)
    def save2(self, word1, word2):
        debug("save2: " + word1 + " " + word2)
        sql = "SELECT word1, word2 FROM word2 WHERE word1='" + word1 + "' AND word2='" + word2 + "'"
        if self._count(sql):
            sql = "UPDATE word2 SET count=count+1 where word1='" + word1 + "' AND word2='" + word2 + "'"
        else:
            sql = "INSERT INTO word2 VALUES('" + word1 + "','" + word2 + "',1)"
        self._sql(sql)
    def save3(self, word1, word2, word3):
        debug("save3: " + word1 + " " + word2 + " " + word3)
        sql = "SELECT word1, word2, word3 FROM word3 WHERE word1='" + word1 + "' AND word2='" + word2 + "' AND word3='" + word3 + "'"
        if self._count(sql):
            sql = "UPDATE word3 SET count=count+1 where word1='" + word1 + "' AND word2='" + word2 + "' AND word3='" + word3 + "'"
        else:
            sql = "INSERT INTO word3 VALUES('" + word1 + "','" + word2 + "','" + word3 + "',1)"
        self._sql(sql)
    def get(self, wordlist, backwards = False, precision = 5):
        if backwards:
            backwards = 1
        else:
            backwards = 0
        sql = "SELECT word" + str((len(wordlist) + 1) - (len(wordlist)) * backwards) + " FROM word" + str(len(wordlist) + 1) + " WHERE word" + str(1 + backwards) + "='" + wordlist[0] + "'"
        if len(wordlist) > 1:
            sql = sql + " AND word" + str(2 + backwards) + " = '" + wordlist[1] + "'"
        sql = sql + " ORDER by count LIMIT " + str(precision) 
        result = self._sql(sql)
        if result:
            return result[randint(0,len(result) - 1)][0]
        return False
    def _sql(self, sql):
        debug(sql)
        self.cursor = self.connection.cursor()
        self.cursor.execute(sql)
        return self.cursor.fetchall()
    def _count(self, sql):
        self._sql(sql)
        return self.cursor.rowcount